package com.caffeinatedbliss.nanowrimo.servlet;

import com.caffeinatedbliss.nanowrimo.NanoWebserviceUtils;
import com.caffeinatedbliss.nanowrimo.PictureGraph;
import org.nanowrimo.ws.NanowrimoWebServiceAPI;
import org.nanowrimo.ws.domain.WordCountSummary;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Paul Hawke
 * Date: Jun 18, 2006
 * Time: 6:01:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class LiveParticipant extends HttpServlet {
  private String supporter;

  public void init(ServletConfig servletConfig) throws ServletException {
    supporter = servletConfig.getInitParameter("supporter");
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    UrlProcessor processor = new UrlProcessor(request);
    int goal = processor.getGoal();
    String uid = processor.getFirstId();

    PictureGraph graph;
    if (uid != null) {
      NanowrimoWebServiceAPI api = new NanowrimoWebServiceAPI();
      try {
        WordCountSummary summary = api.getUserSummary(Integer.parseInt(uid));
        int wordcount = summary.getWordcount();
        if (goal == 50000 && summary.getGoal() != 50000){
          goal = summary.getGoal();
        }
        if ("yes".equals(supporter)) {
          graph = new PictureGraph(summary.getName(), wordcount, goal);
        } else {
          graph = new PictureGraph(wordcount, goal);
        }
      } catch (NumberFormatException e) {
        graph = new PictureGraph("", goal);
      }
    } else {
      String history = request.getParameter("history");
      graph = new PictureGraph(history, goal);
    }
    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(graph.getGraphImage(), "png", os);
    os.close();
  }
}
